<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
    >
      <!-- 左上方菜单 -->
      <template slot="menuLeft">
        <el-button
          type="danger"
          size="small"
          icon="el-icon-delete"
          plain
          v-if="permission.loapriskanalysis_delete"
          @click="handleDelete"
        >
          删 除
        </el-button>
        <el-button
          type="warning"
          size="small"
          plain
          icon="el-icon-download"
          @click="handleExportWord"
        >
          导 出 Word
        </el-button>
      </template>

      <!-- 分析组成员表格自定义 -->
      <template slot="fxzcy" slot-scope="scope">
        <div>{{ formatAnalysisGroupMember(scope.row) }}</div>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  remove,
  getMembers
} from "@/api/saferisk/loapriskanalysis";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";

export default {
  data() {
    return {
      form: {},
      query: {},
      data: [],
      loading: true,
      selectionList: [],
      page: {
        pageSize: this.$pageSize,
        currentPage: 1,
        total: 0
      },
      option: {
        tip: false,
        searchShow: true,
        searchSpan: 6,
        searchMenuSpan: 4,
        border: true,
        index: false,
        viewBtn: true,
        selection: true,
        dialogClickModal: false,
        columnBtn: false,
        addTitle: "风险评估信息",
        column: [
          {
            label: "企业名称",
            prop: "qymc",
            align: "center",
            rules: [
              {
                required: true,
                message: "请输入企业名称",
                trigger: "blur"
              }
            ]
          },
          {
            label: "装置名称",
            prop: "zhmc",
            align: "center",
            search: true
          },
          {
            label: "分析时间",
            prop: "fxsj",
            align: "center",
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd",
            rules: [
              {
                required: true,
                message: "请选择分析时间",
                trigger: "blur"
              }
            ]
          },
          {
            label: "工艺单元",
            prop: "gydy",
            align: "center"
          },
          {
            label: "分析组成员",
            prop: "fxzcy",
            align: "center",
            span: 24,
            multiple: true,
            slot: true,
            type: "tree",
            dicUrl: "/api/riskPoint/riskmanagement/getInternalStaff",
            props: {
              label: "realName",
              value: "id"
            },
            checkStrictly: true
          },
          {
            label: "图纸号",
            prop: "tzh",
            align: "center"
          },
          {
            label: "分析节点",
            prop: "fxjd",
            align: "center",
            search: true
          }
        ],
        // 人员
        mainMembers: {}
      }
    };
  },
  computed: {
    ...mapGetters(["permission"]),

    // LOAP风险分析列表按钮权限
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.loapriskanalysis_add, false),
        viewBtn: this.vaildData(this.permission.loapriskanalysis_view, false),
        delBtn: this.vaildData(this.permission.loapriskanalysis_delete, false),
        editBtn: this.vaildData(this.permission.loapriskanalysis_edit, false)
      };
    },

    // LOAP风险分析列表勾选项ID
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  mounted() {
    this.getmainMembers();
  },
  methods: {
    // 获取人员列表
    getmainMembers() {
      getMembers()
        .then(res => {
          this.mainMembers = {};
          res.data.data.forEach(item => {
            this.mainMembers[item.id] = item.realName;
          });
        })
        .then(() => {
          this.onLoad(this.page);
        });
    },

    // 显示分析组成员列
    formatAnalysisGroupMember(row) {
      if (row.fxzcy === undefined || typeof row.fxzcy === "object") {
        return "";
      }
      var arr = row.fxzcy.split(",");
      var members = [];
      for (let i = 0; i < arr.length; i++) {
        var member =
          this.mainMembers[arr[i]] === undefined
            ? arr[i]
            : this.mainMembers[arr[i]];
        members.push(member);
      }
      return members.join(",");
    },

    // 导出Word
    handleExportWord() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("是否导出LOAP风险点辨识列表?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        window.open(
          `/api/riskIdentification/loapriskanalysis/export?${
            this.website.tokenHeader
          }=${getToken()}&ids=${this.ids}`
        );
      });
    },

    // 新增
    rowSave(row, done) {
      for (let key in row) {
        if (key.indexOf("$") >= 0) {
          delete row[key];
        }
      }
      row.fxzcy = row.fxzcy.join(",");
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        },
        error => {
          loading();
          window.console.log(error);
        }
      );
    },

    // 修改
    rowUpdate(row, index, done) {
      for (let key in row) {
        if (key.indexOf("$") >= 0) {
          delete row[key];
        }
      }
      row.fxzcy = typeof row.fxzcy === "object" ? row.fxzcy.join(",") : row.fxzcy;
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        },
        error => {
          loading();
          console.log(error);
        }
      );
    },

    // 删除一条
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
        });
    },

    // 删除多条
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
          this.$refs.crud.toggleSelection();
        });
    },

    // 打开查看、编辑、新增弹窗前
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },

    // 清空搜索条件
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },

    // 搜索条件改变事件
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },

    // 勾选
    selectionChange(list) {
      this.selectionList = list;
    },

    // 清空勾选
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },

    // 换页数
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },

    // 换每页显示数量
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },

    // 刷新
    refreshChange() {
      this.onLoad(this.page, this.query);
    },

    // 获取表格数据
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style></style>
